﻿/**
* CRL
*/
using CRL.DBAccess;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Reflection;
using CRL.LambdaQuery;
using System.Data;

namespace CRL
{
    public static partial class DbExtensions
    {
        static DbExtensions()
        {
            Init();
        }
        public static void Init()
        {
            SettingConfig.StringFieldLength = 50;
            SettingConfig.CheckModelTableMaping = false;
            SettingConfig.CompileSp = false;
            SettingConfig.UpdateModelCache = false;
        }
        static DBHelper getDBHelper(IDbConnection dbConnection, IDbTransaction dbTransaction = null)
        {
            var builder = DBConfigRegister.GetInstance();
            var dbConnectionTypeName = dbConnection.GetType().Name;
            var dBType = ((DBConfigRegister)builder).GetConnectionTypeMapping(dbConnectionTypeName);
            var dBAccessBuild = new DBAccessBuild(dBType, dbConnection, dbTransaction);
            var helper = DBConfigRegister.GetDBHelper(dBAccessBuild);
            return helper;
        }
        public static IAbsDBExtend GetDBExtend(this IDbConnection dbConnection, IDbTransaction dbTransaction = null)
        {
            var helper = getDBHelper(dbConnection, dbTransaction);
            var dbContext2 = new DbContextInner(helper, new DBLocation() { });
            return DBExtendFactory.CreateDBExtend(dbContext2);
        }
        //static IAbsDBExtend GetDBExtend(this DbContext dbContext)
        //{
        //    var helper = getDBHelper(dbContext);
        //    var dbContext2 = new DbContextInner(helper, new DBLocation() { });
        //    return DBExtendFactory.CreateDBExtend(dbContext2);
        //}
        public static ILambdaQuery<T> GetLambdaQuery<T>(this IDbConnection dbConnection, IDbTransaction dbTransaction = null) where T : class
        {
            var helper = getDBHelper(dbConnection, dbTransaction);
            var db = new DbContextInner(helper, new DBLocation());
            var query = LambdaQueryFactory.CreateLambdaQuery<T>(db);
            return query;
        }
        public static void CreateTable<T>(this IDbConnection dbConnection, IDbTransaction dbTransaction = null)
        {
            var dbExtend = GetDBExtend(dbConnection, dbTransaction);
            ModelCheck.CreateTable(typeof(T), dbExtend as AbsDBExtend, out var message);
            //Console.WriteLine(message);
        }
    }
}

